package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.common.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: VisitorsApiImpl
 * @Author:王晨晗
 * @Description: 访客实现类
 * @Date: 2022/01/06/21:13
 */
@Service
public class VisitorsApiImpl implements VisitorsApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String , String> redisTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private RecommendUserApi recommendUserApi;

    /**
     * @description 保存访问记录
     * @param userId
     * @param visitorUserId
     * @param from
     * @return
     */
    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //查询访客用户在今天是否已经记录过，如果已经记录过，不再记录
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        //构建查询条件
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").gte(minDate),Criteria.where("date").lte(maxDate)));
        //执行查询
        long count = mongoTemplate.count(query, Visitors.class);
        if (count > 0) {
            //今天已经记录过的
            return null;
        }
        Visitors visitors = new Visitors();
        visitors.setFrom(from);     //来源
        visitors.setVisitorUserId(visitorUserId);   //访客id
        visitors.setUserId(userId);     //用户id
        visitors.setDate(System.currentTimeMillis());  //访问时间
        visitors.setId(ObjectId.get());     //访问id

        //存储数据
        mongoTemplate.save(visitors);

        return visitors.getId().toHexString();
    }

    /**
     * @description 根据用户id查询访客记录
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        // 查询前5个访客数据，按照访问时间倒序排序
        // 如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询

        // 上一次查询列表的时间
        Long date = Convert.toLong(redisTemplate.opsForHash().get(VISITOR_REDIS_KEY , String.valueOf(userId)));
        //构建分页条件
        PageRequest pageRequest = PageRequest.of(0 , 5 , Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        //如果redis的日期存在 ,设置日期条件
        if (ObjectUtil.isNotEmpty(date)){
            query.addCriteria(Criteria.where("date").gte(date));
        }
        //执行查询
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        //遍历集合
        for (Visitors visitors : visitorsList) {
            Double score = recommendUserApi.queryScore(userId, visitors.getVisitorUserId());
            if (ObjectUtil.isNotEmpty(score)){
                visitors.setScore(score);
            }else {
                //默认得分
                visitors.setScore(80D);
            }
        }

        return visitorsList;
    }

    /**
     * @description 查询访客列表
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<RecommendUser> queryVisitorList(Long userId, Integer page, Integer pageSize , String nickName) {
        //获取今天的时间戳
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        //构建分页条件
        PageRequest pageRequest = PageRequest.of(page-1 , pageSize);
        //Query query = Query.query(Criteria.where("userId").is(userId).andOperator(Criteria.where("date").gte(minDate),Criteria.where("date").lte(maxDate))).with(pageRequest);
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("date")));
        if (StrUtil.isEmpty(nickName)){
            query.with(pageRequest);
        }

        //执行查询
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        //遍历集合
        List<RecommendUser> list = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            Double score = recommendUserApi.queryScore(userId, visitors.getVisitorUserId());
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setToUserId(visitors.getUserId());    //当前用户
            recommendUser.setUserId(visitors.getVisitorUserId());       //访问用户
            if (ObjectUtil.isNotEmpty(score)){
                recommendUser.setScore(score);
            }else {
                //默认得分
                recommendUser.setScore(85D);
            }
            list.add(recommendUser);
        }
        //修改redis中的时间
        //redisTemplate.opsForHash().put(VISITOR_REDIS_KEY , String.valueOf(userId) , String.valueOf(System.currentTimeMillis()));
        return list;
    }
}
